package net.hserver.sync.util;


import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.core.net.url.UrlPath;
import cn.hutool.core.util.CharsetUtil;

import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class PathUtil {

    public static String pathJoin(String path1, String... path2) {
        String trim = path1.trim();
        if (!trim.startsWith("/")) {
            trim = "/" + trim;
        }
        StringBuilder path1Builder = new StringBuilder(trim);
        for (String s : path2) {
            s = s.trim();
            if (path1Builder.charAt(path1Builder.length() - 1) != '/') {
                path1Builder.append("/");
            }
            if (s.startsWith("/")) {
                path1Builder.append(s.substring(1));
            } else {
                path1Builder.append(s);
            }
        }
        if (path1Builder.charAt(path1Builder.length() - 1) != '/') {
            return path1Builder.toString();
        } else {
            return path1Builder.substring(0, path1Builder.length() - 1);
        }
    }

    public static String pathJoinUrl(String path1, String... path2) {
        UrlBuilder builder = UrlBuilder.of(path1, CharsetUtil.CHARSET_UTF_8);
        for (String s : path2) {
            builder.addPath(s);
        }
        String build = builder.build();
        if (build.endsWith("/")) {
            build = build.substring(0, build.length() - 1);
        }
        return build;
    }

    public static String pathUrlParent(String path1) {
        int i = path1.lastIndexOf("/");
        return path1.substring(0, i);
    }


    public static void main(String[] args) {
        System.out.println(pathJoin("/aaa/", "/111/", "222/", "/333", "/444/", "555", "/333", "7777/", "8888/"));
    }
}
